package com.example.service.impl;

import com.example.service.GetUserToken;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@Service
@RequiredArgsConstructor
public class GetUserTokenImpl implements GetUserToken {

    private static final Logger log = LoggerFactory.getLogger(GetUserTokenImpl.class);

    @Value("${degao.loginUser.facCode}")
    private String facCode;

    @Value("${degao.loginUser.username}")
    private String username;

    @Value("${degao.loginUser.password}")
    private String password;

    @Value("${degao.url.login}")
    private  String getTokenValue ;

    @Autowired
    private RestTemplate restTemplate;

    public String getUserToken() {
        log.info("获取用户TOKEN");
        HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("facCode", facCode);
        body.add("username", username);
        body.add("password", password);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, requestHeader);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(getTokenValue, entity, String.class);
        List<String> cookies = responseEntity.getHeaders().get("Set-Cookie");
        String TOKEN_VALUE;
        if (cookies != null) {
            TOKEN_VALUE = cookies.get(0);
            log.info("TOKEN_VALUE: {}", TOKEN_VALUE);
        } else {
            log.error("cookie 获取失败");
            throw new RuntimeException("cookie 获取失败");
        }
        return TOKEN_VALUE;
    }
}
